<template>
    <div>
        <div class="tips text-center">
            <span class="text-muted">下图展示的最小粒度是月，月份选择框将不再展示</span>
        </div>
        <div class="row">
            <div class="change-type-div">
                <div class="btn-group" role="group" aria-label="Basic example">
                    <button :class="activeMonth" v-on:click="drawBarChartMonth()" type="button">月</button>
                    <button :class="activeQuarter" v-on:click="drawBarChartQuarter()" type="button">季度</button>
                </div>
            </div>
            <div id="compare" class="col-md-12 graph"></div>
        </div>
    </div>
</template>

<script>
    export default {
        name: "BarCompare",
        data () {
            return {
                chart: null,

                year: null,

                loginUser: null,

                // 1代表粒度为月，2代表季度
                type: 1,
            }
        },
        mounted() {
            let _this = this;
            _this.$parent.showYear = true;
            _this.$parent.showMonth = false;
            _this.year = _this.$parent.year;
            // _this.year = 2020;
            if(!_this.year){
                _this.year = new Date().getFullYear();
            }
            _this.type = SessionStorage.get(SESSION_KEY_MONTH_QUARTER) || null;
            if(_this.type === null){
                _this.type = 1;
            }
            _this.loginUser = Tool.getLoginUser();
            _this.type === 1 ? _this.drawBarChartMonth() : _this.drawBarChartQuarter();
        },
        computed:{
            activeMonth(){
                return {
                    'btn btn-outline-primary active': this.type === 1,
                    'btn btn-outline-primary': this.type === 2,
                }
            },
            activeQuarter(){
                return {
                    'btn btn-outline-primary active': this.type === 2,
                    'btn btn-outline-primary': this.type === 1,
                }
            },
        },

        watch:{
            year: {
                handler: function () {
                    this.setTitleOption();
                    this.setDataOption();
                }
            }
        },

        methods: {
            /**
             * 画柱状图通用方法
             */
            drawBarChart(){
                let _this = this;
                SessionStorage.set(SESSION_KEY_MONTH_QUARTER,_this.type);
                if(!_this.chart){
                    _this.chart = _this.$echarts.init(document.getElementById('compare'), 'shine');
                }
                _this.setDefaultOption();
                _this.chart.showLoading();
                _this.setDataOption();
            },
            /**
             * 按粒度为“月”画柱状图
             */
            drawBarChartMonth(){
                let _this = this;
                _this.type = 1;
                _this.drawBarChart();
            },
            /**
             * 按粒度为“季度”画柱状图
             */
            drawBarChartQuarter(){
                let _this = this;
                _this.type = 2;
                _this.drawBarChart();
            },

            /**
             * 得到支出响应数据
             * @returns {Promise<AxiosResponse<any>>}
             */
            getCostResponse(){
                let _this = this;
                return _this.$ajax.get(process.env.VUE_APP_SERVER+'/business/cost/month-cost-sum/'+_this.year + '/' + _this.loginUser.id);
            },

            /**
             * 得到收入响应数据
             * @returns {Promise<AxiosResponse<any>>}
             */
            getIncomeResponse(){
                let _this = this;
                return _this.$ajax.get(process.env.VUE_APP_SERVER+'/business/income/month-income-sum/'+_this.year + '/' + _this.loginUser.id);
            },

            /**
             * 设置数据操作
             */
            setDataOption(){
                let _this = this;
                Promise.all([_this.getCostResponse(),_this.getIncomeResponse()]).then((value)=>{
                    let costList = value[0].data.content;
                    let incomeList = value[1].data.content;
                    for(let i=0;i<costList.length;i++){
                        costList[i] *= -1;
                    }
                    incomeList = incomeList.map(Number);
                    let diffList = [];
                    for(let i=0;i<costList.length;i++){
                        diffList.push(parseFloat(incomeList[i] + costList[i]).toFixed(2));
                    }
                    _this.chart.hideLoading();
                    if(_this.type === 1){
                        _this.chart.setOption({
                            xAxis: [
                                {
                                    data: ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']
                                }
                            ],
                        })
                    }else{
                        let costListQuarter = [];
                        let incomeListQuarter = [];
                        let diffListQuarter = [];
                        let sum = 0;
                        for(let i=0;i<costList.length;i++){
                            sum += costList[i];
                            if((i+1) % 3 === 0){
                                costListQuarter.push(sum);
                                sum = 0;
                            }
                        }
                        for(let i=0;i<incomeList.length;i++){
                            sum += incomeList[i];
                            if((i+1) % 3 === 0){
                                incomeListQuarter.push(sum);
                                sum = 0;
                            }
                        }
                        for(let i=0;i<costList.length;i++){
                            diffListQuarter.push(parseFloat(incomeListQuarter[i] + costListQuarter[i]).toFixed(2));
                        }
                        costList = costListQuarter;
                        incomeList = incomeListQuarter;
                        diffList = diffListQuarter;
                        _this.chart.setOption({
                            xAxis: [
                                {
                                    data: ['第一季度','第二季度','第三季度','第四季度']
                                }
                            ],
                        })
                    }

                    _this.chart.setOption({
                        series: [
                            {
                                name: '差额',
                                type: 'bar',
                                label: {
                                    show: true,
                                    position: 'inside'
                                },
                                data: diffList
                            },
                            {
                                name: '收入',
                                type: 'bar',
                                stack: '总量',
                                label: {
                                    show: true,
                                    position: 'top'
                                },
                                data: incomeList
                            },
                            {
                                name: '支出',
                                type: 'bar',
                                stack: '总量',
                                label: {
                                    show: true,
                                    position: 'bottom'
                                },
                                data: costList
                            },
                        ]
                    })

                })
            },
            /**
             * 设置标题
             */
            setTitleOption(){
                let _this = this;
                let title = _this.type === 1 ? _this.year + '年每月收支情况图' : _this.year + '年每季度收支情况图';
                _this.chart.setOption({
                    title:{
                        left: '2%',
                        right: '4%',
                        text: title
                    }
                })
            },
            /**
             * 设置通用操作
             */
            setDefaultOption(){
                let _this = this;
                _this.setTitleOption();
                let option = {
                    tooltip: {
                        trigger: 'axis',
                        textStyle: {
                            color: 'white'
                        },
                        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                        }
                    },
                    legend: {
                        orient: 'horizontal',
                        top: 30,
                        data: ['差额', '支出', '收入']
                    },
                    toolbox: {
                        feature: {
                            saveAsImage: {}
                        }
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    yAxis: [
                        {
                            type: 'value'
                        }
                    ],
                    xAxis: [
                        {
                            type: 'category',
                            axisTick: {
                                show: false
                            },
                            data: []
                        }
                    ],
                };
                _this.chart.setOption(option);
            }
        }
    }
</script>

<style scoped>
    .btn-group, .tips, .change-type-div{
        margin: 0 auto;
    }

</style>